<?php

/**
 * SysConfigModel 模型
 * Class SysConfigModel
 */
class SysConfigModel extends BaseModel
{

    public $tableName = "sys_config";
    public $errMsg = '';
    static private $allConfig;

    static private $_singleton;

    public function __construct()
    {
        parent::__construct($this->tableName);
    }

    static public function getSingleton()
    {
        if (!self::$_singleton) {
            self::$_singleton = new static();
        }

        return self::$_singleton;
    }

    public function add($data)
    {
        try {
            $selfModel = static::getSingleton();
            return $selfModel->insert([
                'group'       => $data['group'],
                'index'          => $data['index'],
                'show_name'         => $data['show_name'],
                'value'         => $data['value'],
                'description' => $data['description'],
                'create_time'    => time()
            ]);
        } catch (Exception $e) {
            $this->errMsg = $e->getMessage();
            return false;
        }
    }

    //通过index获取配置
    static public function getConfByIndex( $index ){
        $selfModel = static::getSingleton();
        $res = $selfModel->find(['index'=> $index]);
        return $res['value'];
    }

    //获取全局配置
    static public function getAllConfig(){
        if(!self::$allConfig){
            $selfModel = static::getSingleton();
            $all = $selfModel->findAll();
            $nAll = [];
            foreach($all as $val){
                $nAll[$val['index']] = $val['value'];
            }
            self::$allConfig = $nAll;
        }
        return self::$allConfig;
    }
}